package org.example.paymentservice.controller;

import lombok.RequiredArgsConstructor;
import org.example.paymentservice.dto.PaymentRequest;
import org.example.paymentservice.dto.RefundRequest;
import org.example.paymentservice.entity.Order;
import org.example.paymentservice.entity.PaymentTransaction;
import org.example.paymentservice.service.PaymentService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/payments")
@RequiredArgsConstructor
public class PaymentController {
    private final PaymentService paymentService;

    @PostMapping("/process")
    public ResponseEntity<PaymentTransaction> processPayment(@Valid @RequestBody PaymentRequest paymentRequest) {
        PaymentTransaction transaction = paymentService.processPayment(paymentRequest);
        return ResponseEntity.ok(transaction);
    }

    @PostMapping("/refund")
    public ResponseEntity<PaymentTransaction> processRefund(@Valid @RequestBody RefundRequest refundRequest) {
        PaymentTransaction transaction = paymentService.processRefund(refundRequest);
        return ResponseEntity.ok(transaction);
    }

    @GetMapping("/orders/{orderId}")
    public ResponseEntity<Order> getOrder(@PathVariable Long orderId) {
        Order order = paymentService.getOrderById(orderId);
        return ResponseEntity.ok(order);
    }

    @PostMapping("/webhook")
    public ResponseEntity<?> handlePaymentWebhook(@RequestBody String payload) {
        // 处理支付提供商的webhook回调
        // 验证支付状态并更新订单
        paymentService.validatePayment(payload);
        return ResponseEntity.ok().build();
    }
}